package com.houhanzhi.component;

import com.houhanzhi.strategy.ShardingDBConfig;
import com.houhanzhi.strategy.ShardingTableConfig;
import com.houhanzhi.util.CommonUtil;
import org.springframework.stereotype.Component;

@Component
public class ShortLinkComponent {

    private static final String CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";


    /**
     * 创建短链
     *
     * @param originalUrl
     * @return db编码+6位短链编码
     */
    public String createShortLinkCode(String originalUrl) {
        long murmur32 = CommonUtil.murmurHash32(originalUrl);
        //转62进制
        String code = encodeToBase62(murmur32);
        // 配置库表位
        String shortLinkCode = ShardingDBConfig.getRandomDBPrefix(code) + code + ShardingTableConfig.getRandomTableSuffix(code);
        return shortLinkCode;
    }


    /**
     * 10进制转62进制
     *
     * @param num
     * @return
     */
    private static String encodeToBase62(long num) {
        //StringBuffer：线程安全;    StringBuilder：线程不安全
        StringBuffer sb = new StringBuffer();
        do {
            int i = (int) (num % 62);
            sb.append(CHARS.charAt(i));
            num /= 62;
        } while (num > 0);

        String value = sb.reverse().toString();
        return value;
    }
}
